'''
输入两个链表，找出它们的第一个公共结点。

解题思路：若链表有公用的点则之后的点完全相同
首先查找长度，然后将长度缩减值相等
然后齐头并进查找相等的val值返回节点
'''
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        # write code here
        if not pHead1 or not pHead2:
            return None
        cp1 = self.countNode(pHead1)
        cp2 = self.countNode(pHead2)
        if cp1 > cp2:
            while cp1 > cp2:
                pHead1 = pHead1.next
                cp1 -= 1
        else:
            while cp2 > cp1:
                pHead2 = pHead2.next
                cp2 -= 1
        while pHead1.val != pHead2.val:
            if pHead1.next and pHead2.next:
                pHead1 = pHead1.next
                pHead2 = pHead2.next
            else:
                return None
        return pHead1

    def countNode(self, node):
        count = 0
        while node.next:
            node = node.next
            count += 1
        return count